const { Add, Update, Exec, QueryOne, QueryById, ExecGetOne, Query, Execsql_Count } = require('../db/dbhelper');
var { init, format } = require('../models/inviterhistory');
var _ = require('underscore');
var { formatDate, formatDateTime } = require('../libs/common');
var { sendMsg } = require('./wechat');
const { peopleUpdate } = require('./people');
const taskAdd = require('./tasktodo').taskAdd;
const logger = require('../libs/log').logger;
var moment = require('moment');

//审批
const inviterhistoryAudit = async function (doc) {
  try {
    let { id, ispass, commit } = doc;
    if (!id) {
      return {
        code: 1,
        msg: 'id不能为空'
      }
    }
    if (_.isUndefined(ispass)) {
      return {
        code: 1,
        msg: 'ispass不能为空'
      }
    }

    // 获取是否有审批记录，如果有，则记录在历史中audithistory
    let audata = await QueryById('hzz_inviterhistories', doc.id);
    let people = await ExecGetOne(`select cross_realname_auth,cross_work_auth,cross_education_auth,level,confirm from hzz_peoples where code='${audata.pcode}'`);
    if (people.cross_realname_auth != 1){
      return {
        code: 1,
        msg: '审批失败，请先协助用户完成实名认证'
      }
    }else if(people.confirm!=1){
      return {
        code: 1,
        msg: '审批失败，用户未确认'
      }
    } else {
      if (audata.audittime) {
        let his = audata.audithistory ? JSON.parse(audata.audithistory) : [];
        his.push({
          ispass: audata.ispass,
          commit: audata.commit,
          audittime: audata.audittime
        });
        doc.audithistory = JSON.stringify(his);
      }
      doc.audittime = new Date();
      await Update('hzz_inviterhistories', format(doc));
      if (doc.ispass == 1) {
        let send_data = {
          "first": {
            "value": "您提交的推荐人申请已审核！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "平台审核通过！",
            "color": "#173177"
          },
          "keyword2": {
            "value": formatDateTime(new Date()),
            "color": "#173177"
          },
          "remark": {
            "value": "恭喜您成为推荐人，请前往'我的-查看二维码'，邀请更多单身人士加入！",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": "您提交的推荐人申请已通过！"
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('recomreview_tmpid', send_data, audata.pcode, "pages/myInfo/myInfo",send_data_red);
        // 更新用户推荐人信息
        let upData = {
          synopsis: audata.description,
          pcode: audata.pcode,
          isinviter: 1,
          level: 9,
          visterstate: 1
        };
        if (people.level == 1) {
          upData.level = 19;
        } else if (people.level == 0) {
          upData.level = 9;
        }
        peopleUpdate(upData);
        return {
          code: 0,
          msg: '审批成功，已通过'
        }
      } else if (doc.ispass == 9) {
        let send_data = {
          "first": {
            "value": "您提交的推荐人申请已审核！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "平台审核未通过！",
            "color": "#173177"
          },
          "keyword2": {
            "value": formatDateTime(new Date()),
            "color": "#173177"
          },
          "remark": {
            "value": "很遗憾，您的推荐人申请，平台审核未通过，请联系客服咨询！",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": "您提交的推荐人申请未通过！"
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('recomreview_tmpid', send_data, audata.pcode, "pages/myInfo/myInfo",send_data_red);
        // 更新用户推荐人信息
        peopleUpdate({ pcode: audata.pcode, visterstate: 2, isinviter: 0, level:0 });
        return {
          code: 0,
          msg: '审批成功，已驳回'
        }
      }
    } 
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '审批异常'
    }
  }
}
let state = {
  0: '未认证',
  1: '已认证',
  2: '认证中',
  9: '认证失败',
};
//列表
const inviterhistoryList = async function (doc, role) {
  try {
    let { Filter, pagenum, pagesize } = doc;
    let isadmin = role ? role.split(',').includes('hzzadmin') || role.split(',').includes('administrators') || role.split(',').includes('OperationUser'): false;
    let { ispass, isconfirm, nickname, mobile, gender } = Filter;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let sql = 'SELECT * FROM hzz_inviterhistories WHERE 1=1 ';
    let sql_filter = '';
    logger.info('inviterhistoryList----,ispass',ispass)
    if (!!ispass || ispass === '0') {
      sql_filter += ' AND ispass = ' + ispass;
    }
    if (!!isconfirm || isconfirm === '0') {
      sql_filter += ' AND isconfirm = ' + ispass;
    }
    if (!!nickname) {
      sql_filter += ` AND (nickname LIKE '%${nickname}%' OR name LIKE '%${nickname}%') `;
    }
    if(!!mobile){
      sql_filter += ` AND phone like '%${mobile}%' `;
    }
    if(!!gender){
      sql_filter += ' AND grender = ' + gender;
    }
    sql += sql_filter;
    sql += ' ORDER BY isconfirm ASC,ispass ASC,updatetime DESC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    // sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `;
    logger.info('inviterhistoryList--------------,sql,',sql)
    let list = await Exec(sql);
    let peoples = [];
    if (list.length) {
      let pcodes = _.compact(_.pluck(list, 'pcode')).join(',');
      peoples = await Exec(`select code,cross_realname_auth,cross_work_auth,cross_education_auth from hzz_peoples where code in(${pcodes})`);
    }

    let qrcode_list = await Exec(`select * from hzz_qrcodes`);

    let reslist = [];
    for (let index = 0; index < list.length; index++) {
      let item = list[index];
      let pe = _.find(peoples, function (p) {
        return p.code == item.pcode;
      });
      if (pe) {
        item.cross_realname_auth = state[pe.cross_realname_auth];
        item.cross_work_auth = state[pe.cross_work_auth];
        item.cross_education_auth = state[pe.cross_education_auth];
      }
      item.createtime = formatDateTime(item.createtime);
      delete item.updatetime
      item.audittime = formatDateTime(item.audittime);

      let qrcode = _.find(qrcode_list, function (qr) {
        return qr.pcode == item.pcode;
      });
      item.qrcodeURL = qrcode ? qrcode.qrcodeURL : '';
      item.report_url = qrcode ? qrcode.report_url : '';
      item.yusercount = await Execsql_Count(`select count(1) as total from hzz_peoples where invitcode='${item.pcode}' AND (visterstate=9 OR userstate<>9)`);
      item.yusercount_online = await Execsql_Count(`select count(1) as total from hzz_peoples where invitcode='${item.pcode}' AND (visterstate=9 OR userstate<>9) AND online=1`);
      item.yvitercount = await Execsql_Count(`select count(1) as total from hzz_peoples where invitcode='${item.pcode}' AND visterstate<>9`);
      item.yvitercount_online = await Execsql_Count(`select count(1) as total from hzz_peoples where invitcode='${item.pcode}' AND visterstate<>9 AND isinviter=1`);
      if(isadmin){
        item.phone = item.phone? item.phone: '-';
      }else{
        item.phone = item.phone? item.phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2"): '-';
      }
      
      reslist.push(item);
    };

    let total_sql = 'SELECT count(1) as total FROM hzz_inviterhistories  WHERE 1=1 ' + sql_filter;
    logger.info('inviterhistoryList--------------,total_sql,',total_sql)
    let total_data = await Exec(total_sql);
    let total = total_data && total_data.length ? total_data[0].total : 0;

    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list: reslist,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}
// 保存
const inviterhistorySave = async function (doc) {
  try {
    logger.info('---------inviterhistorySave-----------',doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    // 获取用户nickname、name
    let people = await QueryOne('hzz_peoples', { code: doc.pcode }, 'id,nickname,name,phone,cross_realname_auth,cross_work_auth,cross_education_auth,is_father');
    if (people) {
      if (people.cross_realname_auth != 1) {
        return {
          code: 1,
          msg: '申请失败，请先完成个人身份认证！'
        };
      }
    } else {
      return {
        code: 1,
        msg: '申请异常，请退出小程序重新进入！'
      };
    }
    if (!doc.phone) {
      return {
        code: 1,
        msg: '手机号未授权，请在"个人资料"-"联系方式"完善手机号信息！'
      };
    }
    let pl = await QueryOne('hzz_inviterhistories', { pcode: doc.pcode }, null);
    if (pl) {
      doc.id = pl.id;
      doc.ispass = 0;
      await Update('hzz_inviterhistories', format(doc));
    } else {
      await Add('hzz_inviterhistories', init(doc));
    }
    return {
      code: 0,
      msg: '申请成功'
    }
  } catch (error) {
    logger.error('inviterhistorySave=---',error)
    return {
      code: 1,
      msg: error ? error.message : '申请异常，请联系客服'
    }
  }
}
const education_code = {
  '高中及以下': 1,
  '专科': 3,
  '本科': 4,
  '硕士': 5,
  '博士': 6,
};
// 申请成为推荐人-公众号调用
async function inviterApply(doc) {
  try {
    logger.info('-------inviterApply-------doc', doc)
    if (!doc.name) {
      return {
        code: 1,
        msg: '请输入姓名'
      }
    }
    if (!doc.nickname) {
      return {
        code: 1,
        msg: '请输入昵称'
      }
    }
    doc.synopsis = doc.description;
    let people = await ExecGetOne(`select id,code,nickname,invitcode,isinviter from hzz_peoples where  name ='${doc.name}' OR name_father ='${doc.name}' `);
    logger.info('-------inviterApply-------people---', people)
    if (!people) {
      return {
        code: 1,
        msg: '请检查姓名是否填写正确'
      }
    } else {
      if (people.isinviter) {
        logger.info('-------inviterApply-------推荐人申请已通过，无需再次申请', people.code)
        return {
          code: 1,
          msg: '推荐人申请已通过，无需再次申请'
        }
      }
      doc.nickname = doc.nickname ? doc.nickname : people.nickname;
      doc.pcode = people.code;
      if (people.invitcode) {
        // 更新推荐人姓名
        let invisterData = await QueryOne('hzz_peoples', { code: people.invitcode }, 'name,name_father');
        doc.inviter_name = invisterData? (invisterData.name || invisterData.name_father): '';
        sendToInviter(people.invitcode, people.code, doc.nickname);
      }
      let pl = await QueryOne('hzz_inviterhistories', { pcode: doc.pcode }, null);
      if (pl) {
        if (pl.ispass == 1) {
          return {
            code: 1,
            msg: '您已成功申请推荐人，联系客服获取推荐人专属海报'
          };
        } else {
          doc.id = pl.id;
          await Update('hzz_inviterhistories', format(doc));
          return {
            code: 0,
            msg: '您的申请已提交平台，等待管理员审核'
          };
        }
      } else {
        await Add('hzz_inviterhistories', init(doc));

        return {
          code: 0,
          msg: '您的申请已提交平台，等待管理员审核'
        };
      }
    }
  } catch (error) {
    logger.info('---------------error--------', error)
    return {
      code: 1,
      msg: '申请异常，请联系客服'
    };
  }
}
async function sendToInviter(invitcode, pcode, nickname) {
  let task = await QueryOne('hzz_tasktodos', { name: '推荐人申请', pcode: invitcode, gcode: pcode });
  if (task) {
    return;
  }
  taskAdd({ name: '推荐人申请', pcode: invitcode, gcode: pcode });

  // 发送提醒消息 
  let send_data = {
    "first": {
      "value": "您好，您的业务有新进展！",
      "color": "#173177"
    },
    "keyword1": {
      "value": "推荐人申请",
      "color": "#173177"
    },
    "keyword2": {
      "value": `您邀请的[${nickname}]已申请推荐人，快去审核吧！`,
      "color": "#e8320e"
    },
    "remark": {
      "value": '前往"消息-我的待办"进行确认，感谢您的支持',
      "color": "#173177"
    }
  }
  let send_data_red = {
    "thing2": {
      "value": `您邀请的[${nickname}]已申请推荐人，快去审核吧！`
    },
    "time1": {
      "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
    }
  };
  sendMsg('user_confirm', send_data, invitcode, "pages/message/message",send_data_red); //  我的消息
}

async function inviterhistoryQueryOne(doc) {
  try {
    if (!doc.id) {
      return {
        code: 1,
        msg: '请勾选记录'
      }
    }
    let data = await QueryById('hzz_inviterhistories', doc.id);
    return {
      code: 0,
      data: data,
      msg: '获取成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}

async function initViterInfo() {
  try {
    logger.info('---------------init-----开始同步推荐人信息至people---')
    let list = await Query('hzz_inviterhistories', null);
    logger.info('---------------init-----开始同步推荐人信息至people---list', list.length)
    for (let index = 0; index < list.length; index++) {
      const doc = list[index];
      logger.info('---------------init-----开始同步推荐人信息至doc--', doc)
      let peo = await QueryOne('hzz_peoples', { code: doc.pcode, issave: 0 }, 'id');
      if (peo) {
        // 更新用户昵称和描述信息
        let update_peo = {
          id: peo.id,
          nickname: doc.nickname,
          // synopsis: doc.description, 
          grender: doc.grender,
          marital_status: doc.marital_status,
          phone: doc.phone,
          education: doc.education,
          education_code: education_code[doc.education],
          university: doc.university,
          company: doc.company,
          position: doc.position,
          wechat_code: doc.wechat_code,
          email: doc.email
        };
        logger.info('---------------init-----开始同步推荐人信息至update_peo--', update_peo)
        await peopleUpdate(update_peo);
      }
    }
  } catch (error) {
    logger.error('----------init-----error--------', error)
  }
}

async function inviterSaveInfo(doc) {
  try {
    logger.info('---------------inviterSaveInfo-----更新推荐人信息', doc)
    if (!doc.id) {
      return {
        code: 1,
        msg: 'id参数不能为空'
      }
    }
    delete doc.createtime;
    delete doc.updatetime;
    delete doc.audittime;
    await Update('hzz_inviterhistories', format(doc));
    let invdata = await QueryById('hzz_inviterhistories',doc.id);
    doc.pcode = invdata.pcode;
    if (doc.description) {
      await peopleUpdate({ pcode: doc.pcode, synopsis: doc.description });
    }
    if (doc.qywx) {
      logger.info('---------------inviterSaveInfo-----更新用户企业微信')
      await peopleUpdate({ pcode: doc.pcode, qywx: doc.qywx });
    }
    return {
      code: 0,
      message: '保存成功'
    }
  } catch (error) {
    return {
      code: 1,
      message: error ? error.message : '保存异常，请联系客服'
    }
  }
}

async function getInviterListBack(){
  let data = await Exec(`SELECT pcode,name FROM hzz_inviterhistories where ispass=1`);
  return {
    code: 0,
    data: _.pluck(data, 'name')
  }
}


module.exports = {
  inviterhistoryAudit,
  inviterhistoryList,
  inviterhistorySave,
  inviterApply,
  inviterhistoryQueryOne,
  initViterInfo,
  inviterSaveInfo,
  getInviterListBack
}